package com.wen.system.shiro.realm;

import com.wen.common.utils.Md5Util;
import com.wen.common.pojo.system.User;
import com.wen.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Devin QQ:1441289544
 * @description md5加密密码的登录realm
 * @create 2022-02-14 16:10:48
 */

@Slf4j
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        // 判断左边是否是右边的实例 （多realm的话，判断realm中支持哪个token就使用哪个realm）
        return token instanceof UsernamePasswordToken;
    }

    // 可以配置在ShiroConfig中，避免每一个realm都要配密码配置器
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(Md5Util.getDefaultCount());
        super.setCredentialsMatcher(hashedCredentialsMatcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        char[] password = usernamePasswordToken.getPassword();
        String username = usernamePasswordToken.getUsername();
        Object principal = usernamePasswordToken.getPrincipal();
        Object credentials = usernamePasswordToken.getCredentials();

        //按名字查询出来的用户
        User user = userService.findUserByName(username);

        //判断user是否为空
        if (user == null) {
            return null;
        }

        // 获取盐值
        ByteSource byteSource = ByteSource.Util.bytes(Md5Util.getDefaultSalt());
        return new SimpleAuthenticationInfo(user, user.getPassword(), byteSource, getName());
    }

}
